namespace ETestIT.DataAccess
{
    using System;
    using System.Collections.Generic;
    using Domain.Entities;
    using Domain.Repositories;
    using Repository;

    public class CadidateRepositoryImpl : ICadidateRepository
    {
        #region ICadidateRepository Members

        public IList<Candidate> GetAll()
        {
            const string sql = @"SELECT Id, FirstName, Surename, Title  FROM Candidats";

            return new FluentCommand<Candidate>(sql)
                .SetMap(CandidateMap)
                .AsList();
        }

        public void Add(Candidate resume)
        {
            resume.Id = Guid.NewGuid();

            new FluentCommand<string>(
                @"INSERT INTO Candidats (Id ,FirstName ,Surename ,Title)
                                             VALUES (@Id, @FirstName ,@Surename ,@Title)")
                .AddGuid("Id", resume.Id)
                .AddString("FirstName", resume.FirstName)
                .AddString("Surename", resume.Surename)
                .AddString("Title", resume.Title)
                .AsNonQuery();
        }

        public void Update(Candidate candidate)
        {
            new FluentCommand<string>(@"UPDATE Candidats
                                           SET FirstName = @FirstName
                                              ,Surename = @Surename
                                              ,Title = @Title
                                         WHERE Id = @Id")
                .AddGuid("Id", candidate.Id)
                .AddString("FirstName", candidate.FirstName)
                .AddString("Surename", candidate.Surename)
                .AddString("Title", candidate.Title)
                .AsNonQuery();
        }

        public void Delete(Guid candId)
        {
            new FluentCommand<string>(@"DELETE FROM Candidats WHERE Id = @Id")
                .AddGuid("Id", candId)
                .AsNonQuery();
        }

        public Candidate GetById(Guid id)
        {
            const string sql = @"SELECT Id, FirstName, Surename, Title  FROM Candidats WHERE Id = @Id";

            return new FluentCommand<Candidate>(sql)
                .AddGuid("Id", id)
                .SetMap(CandidateMap)
                .AsSingle();
        }

        #endregion

        private Candidate CandidateMap(DataReader reader)
        {
            return new Candidate
                       {
                           Id = reader.GetGuid("Id"),
                           FirstName = reader.GetString("FirstName"),
                           Surename = reader.GetString("Surename"),
                           Title = reader.GetString("Title")
                       };
        }
    }
}